using System;
using System.Collections;
using System.Collections.Generic;

namespace Jonathan.SharpDB
{
	/// <summary>
	/// Sorter for rows in a SharpDB Database.
	/// </summary>
    public class RowSorter : IComparer<ArrayList>
    {
        private SortDirection m_Dir;
        private ColumnType m_Type;
        private int m_Index;

		/// <summary>
		/// Creates a new Sorter.
		/// </summary>
		/// <param name="dir">Sort Direction</param>
		/// <param name="colIndex">Column Index to Sort</param>
		/// <param name="type">Column Type to sort.</param>
        public RowSorter(SortDirection dir, int colIndex, ColumnType type)
        {
            this.m_Dir = dir;
            this.m_Index = colIndex;
            this.m_Type = type;
        }

		/// <summary>
		/// Compares two rows.
		/// </summary>
		/// <param name="rowX">First row to compare.</param>
		/// <param name="rowY">Second row to compare.</param>
		/// <returns>-1,0,1 if First row is less than, equal, or greater than second row.</returns>
        public int Compare(ArrayList rowX, ArrayList rowY)
		{
			if (rowX == null && rowY == null)
			{
				return 0;
			}
			else if (rowX == null && rowY != null)
			{
				return (this.m_Dir == SortDirection.ASCENDING) ? -1 : 1;
			}
			else if (rowY == null && rowX != null)
			{
				return (this.m_Dir == SortDirection.ASCENDING) ? 1 : -1;
			}
			else
			{
				switch (this.m_Type)
				{
					case ColumnType.STRING:
						string strX = rowX[this.m_Index].ToString();
						string strY = rowY[this.m_Index].ToString();
						return (this.m_Dir == SortDirection.ASCENDING) ?
							strX.CompareTo(strY) : strY.CompareTo(strX);
					case ColumnType.INT:
						int intX = Convert.ToInt32(rowX[this.m_Index]);
						int intY = Convert.ToInt32(rowY[this.m_Index]);
						return (this.m_Dir == SortDirection.ASCENDING) ?
							intX.CompareTo(intY) : intY.CompareTo(intX);
					case ColumnType.DECIMAL:
						decimal decX = Convert.ToDecimal(rowX[this.m_Index]);
						decimal decY = Convert.ToDecimal(rowY[this.m_Index]);
						return (this.m_Dir == SortDirection.ASCENDING) ?
							decX.CompareTo(decY) : decY.CompareTo(decX);
					case ColumnType.DATETIME:
						DateTime dtX = DateTime.Parse(rowX[this.m_Index].ToString());
						DateTime dtY = DateTime.Parse(rowY[this.m_Index].ToString());
						return (this.m_Dir == SortDirection.ASCENDING) ?
							dtX.CompareTo(dtY) : dtY.CompareTo(dtX);
				}

				// Default...
				return -1;
			}
        }
	}
}
